package com.Util;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.jooq.Record;
import org.jooq.Result;

/**
 * DESCRIPTION: aa
 *
 * @Author 韩武洽
 * @Date 2016-11
 * @Time 04 14:06
 **/
public class DBUtils {
    public static final String filterStr = "gch_user_general.";

    // 防止其他类调用
    private DBUtils(){

    }

    //将查询数据转换为jsonArray
    public static JsonArray dataChangeJsonArray(Result<Record> record) {
        try {
            // 元数据的数量
            int count = record.fieldsRow().size();
            String[] colNames = new String[count];
            String field = "";
            for(int i = 0; i < count; i++){
                // 字段名称
                field = record.field(i).toString();
                if (field.contains(".")) {
                    colNames[i] = field.substring(field.lastIndexOf(".") + 1,field.length());
                }
                else {
                    colNames[i] = field;
                }
            }

            JsonObject jsonObject = new JsonObject ();
            JsonArray jsonArray = new JsonArray ();
            // 循环结果集列表条数
            for (int i = 0,ii = record.size(); i < ii; i++) {
                jsonObject = new JsonObject ();
                // 循环无数据字段量
                for (int j = 0; j < count; j++) {
                    jsonObject.addProperty(
                            colNames[j].replaceAll("\"",""),
                            record.getValue(i,j) != null ? record.getValue(i,j).toString() : "");
                }
                jsonArray.add(jsonObject);
            }
            return jsonArray;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //将查询数据转换为jsonObject
    public static JsonObject dataChangeJsonObject(Record record) {
        try {
            JsonObject jsonObject = new JsonObject ();
            if (record != null) {
                // 元数据的数量
                int count = record.fieldsRow().size();
                String[] colNames = new String[count];
                String field = "";
                for(int i = 0; i < count; i++){
                    // 字段名称
                    field = record.field(i).toString();
                    if (field.contains(".")) {
                        colNames[i] = field.substring(field.lastIndexOf(".") + 1,field.length());
                    }
                    else {
                        colNames[i] = field;
                    }
                }
                for (int j = 0; j < count; j++) {
                    jsonObject.addProperty(
                            colNames[j].replaceAll("\"",""),
                            record.getValue(j) != null ? record.getValue(j).toString() : "");
                }

                return jsonObject;
            } else  {
                return  jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
